﻿using BarManager.Core.BusinessRules.Interfaces.Specification;
using BarManager.Core.BusinessRules.Interfaces.Validator;
using System.Collections.Generic;
using System.Linq;

namespace BarManager.Core.BusinessRules.Validator
{
    public abstract class BaseValidator<TEntity> : IValidator<TEntity> where TEntity : class
    {
        private ValidatorType Type { get; set; }
        private TEntity EntityToValidate { get; set; }
        private List<Rule<TEntity>> BrokenRulesList { get; set; }

        protected readonly RulesList<TEntity> Rules = new RulesList<TEntity>();

        public bool IsValid(TEntity entity, ValidatorType validatorType)
        {
            this.Type = validatorType;
            this.EntityToValidate = entity;

            BrokenRulesList = Rules.Where(ruleType => ruleType.ValidatorType == Type)
                                    .Where(rule => !rule.Specification.IsSatisfiedBy(EntityToValidate))
                                    .ToList();

            return (BrokenRulesList.Count() <= 0);
        }

        public IEnumerable<string> BrokenRules()
        {
            foreach (var rule in BrokenRulesList)
                foreach (var message in rule.Specification.GetErrorMessage()) 
                    yield return message;
        }
    }
}
